package pers.dawnyang.modular.system.controller;

import java.util.ArrayList;
import java.util.List;
import org.apache.shiro.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.dawnyang.common.domain.Result;
import pers.dawnyang.common.util.ResultUtil;
import pers.dawnyang.config.cache.DictData;
import pers.dawnyang.config.cache.DictUtils;
import pers.dawnyang.modular.system.domain.response.common.DictValue;
import pers.dawnyang.modular.system.service.DictValueService;

/**
 * 公共请求处理
 * 
 * @author dawn yang
 * @date 2021/05/08
 */
@Controller
@RequestMapping("/sys/common")
public class CommonController {

  @Autowired
  private DictValueService dictValueService;

  /**
   * 通过字典编码获取值
   * 
   * @param typeCode
   * @return
   */
  @GetMapping("/getDictValueByCode")
  @ResponseBody
  public Result<List<DictValue>> getDictValueByCode(String typeCode) {
    List<DictValue> list = DictUtils.getDictValueList(typeCode);
    if (null == list || list.size() == 0) {
      list = dictValueService.getDictValueByCode(typeCode);
      DictUtils.setDictValueList(typeCode, list);
    }
    return ResultUtil.success(list);
  }

  /**
   * 前端刷新页面时，获取所有字典
   * 
   * @return
   */
  @GetMapping("/dict")
  @ResponseBody
  public Result<List<DictData>> getDictData() {
    List<DictData> dictDataList = new ArrayList<>();
    Cache<String, Object> cache = DictUtils.getDictData();
    for (String key : cache.keys()) {
      String dictType = key.replace(DictUtils.getCacheName(), "");
      DictData dictData = new DictData();
      List<DictValue> dictValueList = DictUtils.getDictValueList(dictType);
      dictData.setValueList(dictValueList);
      dictData.setTypeCode(dictType);
      dictDataList.add(dictData);
    }
    // System.out.println(dictDataList);
    return ResultUtil.success(dictDataList);
  }

}
